package com.stutter.server;

import com.stutter.client.GreetingService;
import com.stutter.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidText(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 10 characters long");
		}
		
		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);

		
		String temp = "";
		String[] line;
		String delimiter = "\n";
		line = input.split(delimiter);
		String results = new String();
		
		//Read File Line By Line
		   
		 for(int j=0; j< line.length; j++)
			{
				String[] strLine1;
				delimiter = "[:;( .,!?\"-]+\\s*";
				strLine1 = line[j].split(delimiter);
				
				for (int i = 0; i < strLine1.length; i++)   
				{
					//Check for last word in sentence
					if (i+1 > strLine1.length - 1)
					{
						temp = strLine1[i];
						break;		
					}

					if (strLine1[i].equals(strLine1[i+1]))
					{
						results = results + "Repeated word on line " + (j+1) + ": " + strLine1[i] + " " + strLine1[i+1] + "</br>";
					}

					if (temp.isEmpty() == false)
					{
						if (strLine1[i].equals(temp))
						{
							results = results + "Repeated word on line " +(j+1) + ": " + strLine1[i] + " " + temp + "</br>"; 
						}
					}
				}
			}

		return results;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
